import { useEffect, useMemo, useState } from 'react';
import AppList from '../Permission/List';
import TreeList from '../Permission/Tree';
import Permission from '../Permission';
import '../../../style.less';
import { Empty, Spin } from 'antd';
import { getMenuButtonPerm, getMenuTree, getOnlineTree } from '../../../service';
import { TextWidget } from '@inbiz/react';

function Action(props) {
  const { dispatch, appList, permConfig, containerHeight } = props;
  const [outId, $outId] = useState(appList[0]?.OutId); // 应用Id
  const [selectedTreeKeys, $selectedTreeKeys] = useState([]); // 菜单Id
  const [treeList, $treeList] = useState([]); //菜单列表
  const [menuRelationTree, $menuRelationTree] = useState([]); //菜单配置树
  const [selectedButtonKeys, $selectedButtonKeys] = useState([]); // 选中菜单按钮Id
  const [parentId, $parentId] = useState(''); //选中菜单按钮parentId
  const [permissionList, $permissionList] = useState([]); //权限列表
  const [loadding1, $loadding1] = useState(false); //菜单加载
  const [loadding2, $loadding2] = useState(false); //动作加载
  const [loadding3, $loadding3] = useState(false); //子页面加载
  const [childrenList, $childrenList] = useState([]); //子页面列表
  const [selectChildrenPage, $selectChildrenPage] = useState([]); //选中子页面

  // 站点点击，获取对应的菜单
  useEffect(() => {
    cleanData();
    $selectChildrenPage([]);
    $childrenList([]);
    getMenuTreeList();
  }, [outId]);

  // 菜单数据change，初始化选中节点
  useEffect(() => {
    $selectedTreeKeys([treeList[0]?.OutId]);
  }, []);

  // 加载选中菜单配置
  useEffect(() => {
    cleanData();
    $selectChildrenPage([]);
    if (selectedTreeKeys[0]) {
      getChildrenPage(selectedTreeKeys[0]);
    }
  }, [selectedTreeKeys]);

  // 加载选中页面配置
  useEffect(() => {
    cleanData();
    if (selectChildrenPage[0]) {
      getMenuRelationTree(selectChildrenPage[0]);
    }
  }, [selectChildrenPage]);

  const cleanData = () => {
    $menuRelationTree([]);
    $permissionList([]);
    $selectedButtonKeys([]);
  };

  // 菜单动作选中，获取对应的权限
  useEffect(() => {
    if (selectedButtonKeys[0]) {
      getPermissionList();
    } else {
      $permissionList([]);
    }
  }, [selectedButtonKeys]);

  // 获取菜单列表
  const getMenuTreeList = () => {
    if (outId) {
      $loadding1(true);
      // dispatch({
      //   type: 'permissionFun/getMenuTree',
      //   payload: {
      //     siteOutId: outId,
      //     parentOutId: '',
      //   },
      // })
      let payload = {
        siteOutId: outId,
        parentOutId: '',
      };
      getMenuTree(payload).then((res) => {
        $loadding1(false);
        $loadding2(false);
        if (!res) return;
        $treeList(res);
        $selectedTreeKeys([res[0]?.OutId]);
      });
    }
  };
  // 异步加载菜单
  const onLoadData = (treeNode: any) => {
    return new Promise<void>((resolve) => {
      if (treeNode.props.children) {
        resolve();
        return;
      }
      //获取菜单
      // dispatch({
      //   type: 'permissionFun/getChildMenuTree',
      //   payload: {
      //     siteOutId: outId,
      //     parentOutId: treeNode.props.dataRef.OutId,
      //   },
      //   callback: res => {
      //     treeNode.props.dataRef.children = res;
      //     $treeList(updateTreeData(treeList, res, treeNode.props.eventKey))
      //     resolve();
      //   },
      // });
      const payload = {
        siteOutId: outId,
        parentOutId: treeNode.props.dataRef.OutId,
      };
      getMenuTree(payload).then((res) => {
        treeNode.props.dataRef.children = res;
        $treeList(updateTreeData(treeList, res, treeNode.props.eventKey));
        resolve();
      });
    });
  };
  const updateTreeData = (list, children, key) => {
    return list.map((node) => {
      if (node.OutId === key) {
        return {
          ...node,
          children,
        };
      }
      if (node.children) {
        return {
          ...node,
          children: updateTreeData(node.children, key, children),
        };
      }
      return node;
    });
  };
  // 获取子页面
  const getChildrenPage = (menueId: number | string) => {
    if (outId) {
      $loadding3(true);
      // dispatch({
      //   type: 'permissionFun/getOnlineTree',
      //   payload: {
      //     siteOutId: outId,
      //     menuOutId: menueId,
      //     type: 100,
      //   },
      // }).then(res => {
      //   $loadding3(false)
      //   if (!res) {
      //     $childrenList(null);
      //     $selectChildrenPage([])
      //     return;
      //   }
      //   $selectChildrenPage([res?.[0]?.Id])
      //   $childrenList(formateRelationTree(res, true));
      // })
      const payload = {
        siteOutId: outId,
        menuOutId: menueId,
        type: 100,
      };
      getOnlineTree(payload).then((res) => {
        $loadding3(false);
        if (!res) {
          $childrenList(null);
          $selectChildrenPage([]);
          return;
        }
        $selectChildrenPage([res?.[0]?.Id]);
        $childrenList(formateRelationTree(res, true));
      });
    }
  };

  //获取菜单动作
  const getMenuRelationTree = (pageOutId) => {
    if (outId && pageOutId) {
      $loadding2(true);
      // dispatch({
      //   type: 'permissionFun/getOnlineTree',
      //   payload: {
      //     siteOutId: outId,
      //     menuOutId: selectedTreeKeys[0],
      //     pageOutId,
      //     type: 200,
      //   },
      // }).then(res => {
      //   $loadding2(false)
      //   if (!res) {
      //     $menuRelationTree(null);
      //     $selectedButtonKeys([])
      //     return;
      //   }
      //   $menuRelationTree(formateRelationTree(res));
      // })
      const payload = {
        siteOutId: outId,
        menuOutId: selectedTreeKeys[0],
        pageOutId,
        type: 200,
      };
      getOnlineTree(payload).then((res) => {
        $loadding2(false);
        if (!res) {
          $menuRelationTree(null);
          $selectedButtonKeys([]);
          return;
        }
        $menuRelationTree(formateRelationTree(res));
      });
    }
  };
  //格式化菜单动作数据
  const formateRelationTree = (data, selectable?) => {
    data.forEach((item) => {
      item.Name = item.ObjectName;
      item.children = item.Children?.length ? formateRelationTree(item.Children) : null;
      item.isLeaf = item.Children?.length ? false : true;
      item.selectable = selectable ? selectable : !item.ParentId ? false : true;
      item.OutId = item.Id;
    });
    return data;
  };
  // 获取权限列表
  const getPermissionList = (txt?) => {
    const [id] = selectedButtonKeys;
    if (id) {
      // dispatch({
      //   type: 'permissionFun/getMenuButtonPerm',
      //   payload: {
      //     menuOutId: selectedTreeKeys[0],
      //     entityId: id,
      //     searchText: txt || '',
      //   },
      // }).then(res => {
      //   if (!res) return
      //   $permissionList(res)
      // });
      const payload = {
        menuOutId: selectedTreeKeys[0],
        entityId: id,
        searchText: txt || '',
      };
      getMenuButtonPerm(payload).then((res) => {
        if (!res) return;
        $permissionList(res);
      });
    }
  };

  const findparentId = (array, id) => {
    let parentId = null;
    array.forEach((item) => {
      if (item.children && findparentId(item.children, id)) {
        parentId = findparentId(item.children, id);
      }
      if (item.OutId == id) {
        parentId = item.ParentOutId;
      }
    });
    return parentId;
  };
  // 判断是否是ifream嵌套
  const isIframe = useMemo(() => {
    return location?.hash?.indexOf('permissionFun') != -1;
  }, []);

  return (
    <div className={'main'} style={{ height: `calc(${containerHeight} - 144px)` }}>
      <div className={'appList'}>
        <AppList
          outId={outId}
          appClick={(res) => {
            $permissionList([]);
            $outId(res);
          }}
          list={appList}
        />
      </div>

      <div className={'treeList'}>
        {treeList.length ? (
          <TreeList
            key={outId}
            list={treeList}
            onLoadData={onLoadData}
            selectedKeys={selectedTreeKeys}
            treeClick={(arr) => $selectedTreeKeys(arr)}
          />
        ) : loadding1 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
      <div className={'treeList'}>
        {childrenList.length ? (
          <TreeList
            key={outId}
            list={childrenList}
            // onLoadData={onLoadData}
            selectedKeys={selectChildrenPage}
            treeClick={(arr) => {
              console.log(arr);
              $selectChildrenPage(arr);
            }}
          />
        ) : loadding3 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>
      <div className={'treeList'}>
        {menuRelationTree?.length ? (
          <TreeList
            key={outId}
            list={menuRelationTree}
            // onLoadData={onLoadData}
            selectedKeys={selectedButtonKeys}
            treeClick={(arr) => {
              // 查找选中节点的parentId
              $parentId(findparentId(menuRelationTree, arr[0]));
              $selectedButtonKeys(arr);
            }}
          />
        ) : loadding2 ? (
          <Spin className={'spindiv'} />
        ) : (
          <Empty
            className={'spindiv'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>Permission.noData</TextWidget>}
          />
        )}
      </div>

      <div className={`${isIframe ? 'iframePerm' : 'permission'}`}>
        <Permission
          key={selectedButtonKeys[0]}
          dispatch={dispatch}
          treeList={treeList}
          list={permissionList}
          outId={outId}
          menuId={selectedButtonKeys[0]}
          onRefresh={getPermissionList}
          permtype={'action'}
          menuOutId={selectedTreeKeys[0]}
          parentId={parentId}
          permConfig={permConfig}
        />
      </div>
    </div>
  );
}

export default Action;
